<?php
/**
 * Created by PhpStorm.
 * User: stupboy
 * Date: 2018/2/26
 * Time: 17:35
 */

namespace app\base\service;

use app\base\model;

/**
 * 隐号拨打服务
 * @package app\base\service
 */
class Phone
{
    public $spid = '853610';        //spid
    public $appid = '097';        //appid
    public $passwd = 'jjcx&nacx2018';    //密码
    public $areacode = '595';    //区号

    /**
     * 解除小号绑定
     * @param string $relate_id
     * @return xml
     **/
    public function dial_close($relate_id)
    {
        $MethodName    = 'XH_CLOSE2';
        $timestamp     = date('YmdHis');
        $authenticator = sha1($timestamp . $MethodName . $this->spid . $this->passwd);
        $xml           = '<Request><Head><MethodName>' . $MethodName . '</MethodName><Spid>' . $this->spid . '</Spid><Appid>' . $this->appid . '</Appid><Passwd>' . sha1($this->passwd) . '</Passwd><Timestamp>' . $timestamp . '</Timestamp><Authenticator>' . $authenticator . '</Authenticator></Head><Body><RelatedId>' . $relate_id . '</RelatedId></Body></Request>';
        $url           = 'http://110.84.128.78:8088/httpIntf/dealIntf?postData=' . urlencode($xml);
        $xml_ret       = file_get_contents($url);
        $res           = $this->parseXML($xml_ret, 'Result');
        if($res == 0){
            (new model\Dial())->save(['status' => 0],['RelatedId' => $relate_id]);
        }
        return $xml_ret;
    }

    /**
     * 获取打电话的小号，如果这个小号已经绑定，则解除绑定
     * @param string $Telno1
     * @param string $Telno2
     * @param number $applyId
     * @return number
     */
    public function dial_get($Telno1, $Telno2, $applyId)
    {
        //把号码中的“-”替换为空
        $Telno1 = str_replace("-", "", $Telno1);
        $Telno2 = str_replace("-", "", $Telno2);
        //不允许自己的号码跟自己的号码通过小号绑定
        if ($Telno1 == $Telno2) return 0;
        $Model  = new model\Dial();
        $return = $Model->where(['Telno1' => $Telno1, 'Telno2' => $Telno2, 'status' => 1])->order('id desc')->find();
        if (!$return) $return = $Model->where(['Telno1' => $Telno2, 'Telno2' => $Telno1, 'status' => 1])->order('id desc')->find();
        //如果两个号码恰好存在绑定关系且当前订单id与数据库中的id相同，则直接返回小号
        if ($return && $return['applyId'] == $applyId) {
            //设置回调
            //$this->callback($return['applyId'], $return['RelatedId']);//回调地址只需要设置一次
            return $return['XhTel'];
        }
        //如果主叫号码（$Telno1）存在绑定关系，则不管在数据库中的该号码是主叫还是被叫，如果有绑定关系的，都获取数据下来，并去解除绑定关系，同时把status设置为0
        $return = $Model->where(['status' => 1])->where('Telno1="' . $Telno1 . '" or Telno2="' . $Telno1 . '"')->field('id,RelatedId')->order('id desc')->find();
        if ($return) {
            //调用解绑
            $xml_ret = $this->dial_close($return['RelatedId']);
            $res     = $this->parseXML($xml_ret, 'Result');
            if ($res == 0) {
                //把状态设置为解除绑定
                $Model->save(['status' => 0],['id' => $return['id']]);
            } else {
                // 解除小号绑定失败，记录日志
                // log::record('解除小号绑定失败：' . $xml_ret);
            }
        }
        //重新获取小号
        $MethodName    = 'XH_DIAL2';
        $timestamp     = date('YmdHis');
        $authenticator = sha1($timestamp . $MethodName . $this->spid . $this->passwd);
        $head          = '<Head><MethodName>' . $MethodName . '</MethodName><Spid>' . $this->spid . '</Spid><Appid>' . $this->appid . '</Appid><Passwd>' . sha1($this->passwd) . '</Passwd><Timestamp>' . $timestamp . '</Timestamp><Authenticator>' . $authenticator . '</Authenticator></Head>';
        $body          = '<Body><AreaCode>595</AreaCode><Telno1>' . $Telno1 . '</Telno1><Telno2>' . $Telno2 . '</Telno2></Body>';
        $xml           = '<Request>' . $head . $body . '</Request>';
        $url           = 'http://110.84.128.78:8088/httpIntf/dealIntf?postData=' . urlencode($xml);
        $xml_ret       = file_get_contents($url);
        $XhTel         = $this->parseXML($xml_ret, 'XhTel');//小号
        $RelatedId     = $this->parseXML($xml_ret, 'RelatedId');//关联ID
        if ($XhTel) {
            //获取小号成功，则开始设置回调接口
            //$this->callback($applyId, $RelatedId);//回调地址只需要设置一次
            if (strpos($XhTel, '86') === 0) $XhTel = '0' . ltrim($XhTel, '86');
            $data = [
                'applyId' => $applyId,
                'XhTel' => $XhTel,
                'RelatedId' => $RelatedId,
                'Telno1' => $Telno1,
                'Telno2' => $Telno2,
                'TimeCreate' => time(),
            ];
            return $Model->save($data) ? $XhTel : 0;
        }
        return 0;
    }


    /**
     * 设置小号账单的回调
     * @return number    0表示失败，1表示成功
     *   */
    public function callback()
    {
        //统一把账单回调放到晋江
        $url = 'http://api.jjcxfw.com/home/bill/record';
        $base64url = base64_encode($url);
        $MethodName = 'BILLS_URL';
        $timestamp = date('YmdHis');
        $authenticator = sha1($timestamp . $MethodName . $this->spid . $this->passwd);
        $head = '<Head><MethodName>' . $MethodName . '</MethodName><Spid>' . $this->spid . '</Spid><Appid>' . $this->appid . '</Appid><Passwd>' . sha1($this->passwd) . '</Passwd><Timestamp>' . $timestamp . '</Timestamp><Authenticator>' . $authenticator . '</Authenticator></Head>';
        $body = '<Body><Url>' . $base64url . '</Url></Body>';
        $xml = '<Request>' . $head . $body . '</Request>';
        $url = 'http://110.84.128.78:8088/httpIntf/dealIntf?postData=' . urlencode($xml);
        $xmlret = file_get_contents($url);
        //如果没有错误，则返回true，即1
        if ($this->parseXML($xmlret, 'Result') == 0) {
            return 1;
        } else {
            //记录日志：
            log::record('设置回调地址失败：' . $xmlret);
            return 0;
        }
    }


    /**
     * 解析返回的XML数据
     * @param string $xml
     * @param string $key
     * @return unknown|string
     */
    private function parseXML($xml, $key)
    {
        $pattern = '/<' . $key . '>(.*)<\/' . $key . '>/';
        preg_match($pattern, $xml, $result);
        if ($result) {
            return $result[1];
        }
        return '';
    }
}